/*
 * @(#)AbstractMonitorNotice.java   1.0  2022年3月15日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.monitor.core.notice;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swift.monitor.core.point.AlarmLevel;
import com.swift.monitor.core.point.Point;
import com.swift.util.exec.ThreadUtil;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2022年3月15日
 */
public abstract class AbstractMonitorNotice<T extends Point> implements MonitorNotice<T> {

    protected static final Logger log = LoggerFactory.getLogger(AbstractMonitorNotice.class);

    private Queue<T> queue = new ConcurrentLinkedQueue<>();

    public AbstractMonitorNotice() {
        new ThreadPointMath().start();
    }
    
    public void setAlarmLevel(Point t,String lateKey,int warn,int error) {
        double late = t.getDouble(lateKey, 0);
        if(late<=0) return;
        if(late>warn) {
            if(t.getLevel().getLevel()<AlarmLevel.WARN.getLevel()) t.setLevel(AlarmLevel.WARN);
        }
        if(late>error) {
            if(t.getLevel().getLevel()<AlarmLevel.ERROR.getLevel()) t.setLevel(AlarmLevel.ERROR);
        }
        t.setAlarmInfo(t.getAlarmInfo()+lateKey+" the utilization rate is :"+late+";");
    }

    private class ThreadPointMath extends Thread {

        private ThreadPointMath() {
            this.setDaemon(true);
            this.setName("ThreadPointMath");
        }

        public void run() {
            while (true) {
                try {
                    T t = queue.poll();
                    if (t == null) {
                        ThreadUtil.sleep(300);
                        continue;
                    }
                    doNotice(t);
                } catch (Throwable ex) {
                    log.error("监控线程定时器异常", ex);
                    ThreadUtil.sleep(300);
                }
            }
        }
    }

    @Override
    public void notice(T t) {
        queue.add(t);
    }
    
    protected abstract void doNotice(T t);
}
